﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GoogleNewsProvider;
using System.Text;
using System.Web.Script.Serialization;
using GeoZoneWeb.Class;
using System.Net;
using System.IO;
using Newtonsoft.Json;
using GeoZoneDAL;

namespace GeoZoneWeb
{
    public partial class WazeMap : System.Web.UI.Page
    {
        #region Consts
        const string WAZETOKEN = @"e99d8716-5a99-4907-a939-bb99dba7e025";
        #endregion

        #region Private members
        private List<Yishuvim> yishuvimList = null;
        #endregion

        #region Page events



        protected void Page_Load(object sender, EventArgs e)
        {
            FillYishuvimList();
            GNews gNews = new GNews();
            List<GNewsItem> gNewsNationlist = gNews.ParseGoogleRSSNews(NewsType.Nation);
            GNewsItem tmpGNewsItem = gNewsNationlist[0];
            //AddNewPopupToMap(34.79000, 32.08600, tmpGNewsItem.Title, tmpGNewsItem.Description, tmpGNewsItem.Link, tmpGNewsItem.Category, tmpGNewsItem.PubDate);
            AddNewPopupToMap(34.79000, 32.08600, tmpGNewsItem.Title, tmpGNewsItem.Description, tmpGNewsItem.Link, tmpGNewsItem.Category, tmpGNewsItem.PubDate);
            GeoLocation geoSearchRes = GeoLocateAddress("ירושלים", "34.79000", "32.08600");
        }
       
        protected void btnLocateMe_Click(object sender, EventArgs e)
        {

        }
        #endregion

        #region Helper methods
        void AddNewPopupToMap(double longVal,double latVal,string newsTitle,string newsDescription,string newsLink,string newsCategory,string newsPubDate)
        {
            DateTime tmpDate = DateTime.MinValue;
            DateTime.TryParse(newsPubDate.Remove(newsPubDate.IndexOf("GMT+")), out tmpDate);
            if (tmpDate != DateTime.MinValue)
            {
                newsPubDate = tmpDate.ToString(@"dd/MM/yyyy HH:mm");
            }
            string newsMarkerTemplate =
                string.Concat(
                @"listOfMarkers.push(""addNewsMarker(",
                longVal, ",",
                latVal, ",'",
                EncodeJsString(newsTitle), "','",
                EncodeJsString(newsDescription), "','",
                EncodeJsString(newsLink), "','",
                EncodeJsString(newsPubDate), "','",
                EncodeJsString(newsCategory), @"');"");");
            this.Page.ClientScript.RegisterStartupScript(this.GetType(),"AddNewsMarkerJS", newsMarkerTemplate,true); 
        }

        /// <summary>
        /// Encodes a string to be represented as a string literal. The format
        /// is essentially a JSON string.
        /// 
        /// The string returned includes outer quotes 
        /// Example Output: "Hello \"Rick\"!\r\nRock on"
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public string EncodeJsString(string s)
        {
            s = s.Replace("'",string.Empty);
            StringBuilder sb = new StringBuilder();
            //sb.Append("\"");
            foreach (char c in s)
            {
                switch (c)
                {
                    case '\"':
                        sb.Append("\\\"");
                        break;
                    case '\\':
                        sb.Append("\\\\");
                        break;
                    case '\b':
                        sb.Append("\\b");
                        break;
                    case '\f':
                        sb.Append("\\f");
                        break;
                    case '\n':
                        sb.Append("\\n");
                        break;
                    case '\r':
                        sb.Append("\\r");
                        break;
                    case '\t':
                        sb.Append("\\t");
                        break;
                    default:
                        /*int i = (int)c;
                        if (i < 32 || i > 127)
                        {
                            sb.AppendFormat("\\u{0:X04}", i);
                        }
                        else
                        {*/
                            sb.Append(c);
                        /*}*/
                        break;
                }
            }
            //sb.Append("\"");
            return sb.ToString();
        }

        private HttpWebRequest GetWebRequest(string formattedUri)
        {
            // Create the request’s URI.
            Uri serviceUri = new Uri(formattedUri, UriKind.Absolute);
            // Return the HttpWebRequest.
            return (HttpWebRequest)System.Net.WebRequest.Create(serviceUri);
        }
        
        GeoLocation GeoLocateAddress(string address,string longVal,string latVal)
        {
            string wazeGeolocationRestURL = string.Format(@"http://www.waze.co.il/WAS/mozi?q={0}&token={1}&lon={2}&lat={3}", Server.UrlEncode(address), WAZETOKEN, longVal, latVal);
            HttpWebRequest webRequest = GetWebRequest(wazeGeolocationRestURL);
            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
            string jsonResponse = string.Empty;
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                jsonResponse = sr.ReadToEnd();
            }
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            bounds deserializedBounds = serializer.Deserialize<bounds>(jsonResponse.Replace("[",string.Empty).Replace("]",string.Empty));

            GeoLocation retObj = new GeoLocation();
            retObj.Address = deserializedBounds.mobileResult;
            retObj.Lat = deserializedBounds.location.lat;
            retObj.Long = deserializedBounds.location.lon;
            retObj.Name = deserializedBounds.name;
            return retObj;
        }

        void FillYishuvimList()
        {
            DAL dal = new DAL();
            yishuvimList = dal.GetAllYishuvim();
        }
        #endregion
    }
}
